@file:Suppress("unused")

package com.hjh.tool.util

import android.graphics.Bitmap
import com.elvishew.xlog.XLog
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import androidx.core.graphics.createBitmap

/**
 * @author： hjh
 * @createDate： 2025/6/10 14:11
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
object BarcodeUtil {
    fun String?.generateBarcode(width: Int, height: Int): Bitmap? {
        if (this == null) return null
        try {
            // 使用正确的提示类型，这里设置字符编码为 UTF-8
            val hints = mutableMapOf<EncodeHintType, Any>()
            hints[EncodeHintType.CHARACTER_SET] = "UTF-8"

            val multiFormatWriter = MultiFormatWriter()
            val bitMatrix =
                multiFormatWriter.encode(this, BarcodeFormat.CODE_128, width, height, hints)

            val pixels = IntArray(width * height)
            for (y in 0 until height) {
                for (x in 0 until width) {
                    pixels[y * width + x] = if (bitMatrix.get(x, y)) {
                        0xFFFFFFFF.toInt()  // 白色
                    } else {
                        0xFF000000.toInt()  // 黑色
                    }
                }
            }

            return createBitmap(width, height).apply {
                setPixels(pixels, 0, width, 0, 0, width, height)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            XLog.e("$this 条形码生成失败: ${e.message}")
            return null
        }
    }
}